package com.example.chenjun.myapplication.net.netcallback;

import com.example.chenjun.myapplication.util.TypeUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.lang.reflect.Type;

public abstract class BaseCallback<T> implements NetCallback<T> {
    private JSONObject mJson;
    private static final String SUCCESS = "200";
    protected Type mType;

    @Override
    public T parse(String str) throws NullPointerException {
        mType = TypeUtil.getType(this);
        if (mType == null){
            throw new NullPointerException("type == null");
        }
        try {
            mJson = new JSONObject(str);
            if (isSuccess()){
                return this.parse(mJson);
            }else {
                onError(new Exception(mJson.optString("resultcode")));
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }

    protected abstract T parse(JSONObject json);

    private boolean isSuccess() {
        return mJson != null && SUCCESS.equals(mJson.optString("resultcode"));
    }
}
